from typing import Dict, Optional
from datetime import datetime
from decimal import Decimal


class AssetManager:
    """
    资产管理引擎
    负责管理用户的资产信息，包括总资产、可用资金、持仓市值和当日盈亏。
    其他模块（如持仓管理器）通过此引擎获取资产状态，并在买卖股票时更新资产。
    """

    def __init__(self, initial_capital: float = 1000000.0):
        """构造函数"""
        self.account = {
            "total_asset": initial_capital,  # 总资产
            "available": initial_capital,    # 可用资金
            "market_value": 0.0,            # 持仓市值
            "daily_pnl": 0.0                # 当日盈亏
        }
        self.last_update_time: Optional[datetime] = None  # 最后更新时间
        
    def set_last_update_time(self, last_update_time: datetime):
        """设置最后更新时间"""
        self.last_update_time = last_update_time

    def get_total_asset(self) -> float:
        """获取总资产"""
        return self.account["total_asset"]

    def get_available_capital(self) -> float:
        """获取可用资金"""
        return self.account["available"]

    def get_market_value(self) -> float:
        """获取持仓市值"""
        return self.account["market_value"]

    def get_daily_pnl(self) -> float:
        """获取当日盈亏"""
        return self.account["daily_pnl"]

    def update_position_value(self, position_value: float) -> None:
        """更新持仓市值"""
        self.account["market_value"] = position_value
        print(f"更新持仓市值: {self.account['market_value']}")
        self.account["total_asset"] = self.account["available"] + self.account["market_value"]

    def update_daily_pnl(self, pnl: float) -> None:
        """更新当日盈亏"""
        self.account["daily_pnl"] = pnl

    def update_account(self, account: Dict) -> None:
        """更新账户信息"""
        self.account.update({
            "total_asset": account["total_asset"],
            "available": account["available"],
            "market_value": account["market_value"],
            "daily_pnl": account["daily_pnl"]
        })

    def deposit(self, amount: float) -> bool:
        """存入资金"""
        if amount <= 0:
            return False
        self.account["available"] += amount
        self.account["total_asset"] += amount
        return True

    def withdraw(self, amount: float) -> bool:
        """提取资金"""
        if amount <= 0 or amount > self.account["available"]:
            return False
        self.account["available"] -= amount
        self.account["total_asset"] -= amount
        return True

    def buy(self, cost: float) -> bool:
        """买入股票，扣除可用资金"""
        if cost > self.account["available"]:
            return False
        self.account["available"] -= cost
        return True

    def sell(self, income: float) -> None:
        """卖出股票，增加可用资金"""
        self.account["available"] += income

    def save(self) -> Dict:
        """保存资产状态"""
        return self.account.copy()

    def load(self, data: Dict) -> None:
        """加载资产状态"""
        self.account = {
            "total_asset": data.get("total_asset", self.account["total_asset"]),
            "available": data.get("available", self.account["available"]),
            "market_value": data.get("market_value", self.account["market_value"]),
            "daily_pnl": data.get("daily_pnl", self.account["daily_pnl"])
        }

    def get_account(self) -> Dict:
        """获取账户信息"""
        return self.account.copy()